package com.geeklan.smart.ui.main;

import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.lifecycle.ViewModelProvider;

import com.geeklan.base.base.BaseActivity;
import com.geeklan.base.utils.ActivityUtil;
import com.geeklan.base.utils.MLog;
import com.geeklan.smart.MLMApplication;
import com.geeklan.smart.R;
import com.geeklan.smart.data.model.UmengMessage;
import com.geeklan.smart.data.remote.IpApiClient;
import com.geeklan.smart.data.repository.pet.PetRepository;
import com.geeklan.smart.databinding.ActivityMainBinding;
import com.geeklan.smart.event.LoginOut;
import com.geeklan.smart.ui.dialog.LoginAlertDialog;
import com.geeklan.smart.ui.dialog.PushMessageAlertDialog;
import com.geeklan.smart.ui.login.LoginActivity;
import com.geeklan.smart.ui.main.frament.HomeFragment;
import com.geeklan.smart.ui.main.frament.MeFragment;
import com.geeklan.smart.ui.message.MessageListActivity;
import com.geeklan.smart.ui.viewmodel.pet.PetViewModel;
import com.geeklan.smart.ui.viewmodel.pet.PetViewModelFactory;
import com.geeklan.smart.utils.DateUtils;
import com.geeklan.smart.utils.SharedPreferencesUtil;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

public class MainActivity extends BaseActivity<ActivityMainBinding> {
    private static final String TAG = "MainActivity";
    private HomeFragment homeFragment;
    private MeFragment meFragment;
    private PetViewModel petViewModel;

    @Override
    public boolean isRegisterEvent() {
        return true;
    }

    @Override
    protected void onApplyWindowInsets() {
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, 0, systemBars.right, systemBars.bottom);
            return insets;
        });
    }

    @Override
    protected ActivityMainBinding initBinding() {
        return ActivityMainBinding.inflate(getLayoutInflater());
    }

    @Override
    protected void initData() {
        petViewModel = new ViewModelProvider(this, new PetViewModelFactory(new PetRepository())).get(PetViewModel.class);

        petViewModel.getUpdateFeedPlanLiveData().observe(this, response -> {
            dismiss();
            Toast.makeText(this, R.string.update_success, Toast.LENGTH_SHORT).show();
        });

        petViewModel.getUpdateFeedPlanErrorLiveData().observe(this, s -> {
            dismiss();
            Toast.makeText(this, s, Toast.LENGTH_SHORT).show();
        });

        IpApiClient apiClient = new IpApiClient();
        apiClient.getIpDataAsync();
    }


    @Override
    protected void initView() {
        homeFragment = new HomeFragment();
        meFragment = new MeFragment();

        getSupportFragmentManager().beginTransaction()
                .replace(R.id.fragmentContainer, homeFragment)
                .commit();

        mBinding.llHome.setOnClickListener(v -> {
            mBinding.tvHome.setTextColor(getColor(R.color.color_ff010101));
            mBinding.tvMe.setTextColor(getColor(R.color.color_acacac));

            mBinding.ivHome.setImageResource(R.drawable.ic_home_selected);
            mBinding.ivMe.setImageResource(R.drawable.ic_me_unselected);

            getSupportFragmentManager().beginTransaction()
                    .replace(R.id.fragmentContainer, homeFragment)
                    .commit();
        });
        mBinding.llMe.setOnClickListener(v -> {
            mBinding.tvHome.setTextColor(getColor(R.color.color_acacac));
            mBinding.tvMe.setTextColor(getColor(R.color.color_ff010101));

            mBinding.ivHome.setImageResource(R.drawable.ic_home_unselected);
            mBinding.ivMe.setImageResource(R.drawable.ic_me_selected);

            getSupportFragmentManager().beginTransaction()
                    .replace(R.id.fragmentContainer, meFragment)
                    .commit();
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(LoginOut event) {
        logoutAndRedirectToLogin();
    }

    private PushMessageAlertDialog alertDialogType_2;
//    private PushMessageAlertDialog alertDialog;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(UmengMessage event) {
        String title = event.getTitle();
        String content = event.getContent();
        String msgType = event.getMsgType();
        String ask_time = event.getAsk_time();
        if (MLMApplication.getApplication().isAppInForeground(this)) {//在前台直接弹框

            if ("2".equals(msgType)) {
                if (!DateUtils.isMoreThanFiveMinutes(ask_time)) {
//                    if(alertDialogType_2 == null || !alertDialogType_2.isShowing()) {
                        alertDialogType_2 = new PushMessageAlertDialog(this, title, content);
                        MLog.i("没有超过5分钟");
                        alertDialogType_2.setShowRelativeLayoutButton(v1 -> {
                            alertDialogType_2.dismiss();
                            event.setStatus(1);
                            petViewModel.confirmTimeFeed(event);
                        }, v1 -> {
                            alertDialogType_2.dismiss();
                            event.setStatus(0);
                            petViewModel.confirmTimeFeed(event);
                        });
                        alertDialogType_2.show();
//                    }
                } else {
                    MLog.i("超过5分钟");
                }
            } else {
//                if(alertDialog == null || !alertDialog.isShowing()) {
//                    alertDialog = new PushMessageAlertDialog(this, title, content);
//                    alertDialog.setShowRelativeLayoutButton(v1 -> {
//                        alertDialog.dismiss();
//                        MessageListActivity.startActivity(this);
//                    }, v1 -> alertDialog.dismiss());
//                    alertDialog.show();
//                }
            }
        }
    }

    private LoginAlertDialog loginOutAlertDialog;

    public void logoutAndRedirectToLogin() {
        ActivityUtil.getInstance().finishAllActivityExcept(MainActivity.class);
        if (loginOutAlertDialog == null) {
            loginOutAlertDialog = new LoginAlertDialog(this, "验证信息");
            loginOutAlertDialog.setOnButtonClickListener(v -> {
                loginOutAlertDialog.dismiss();
            });
            loginOutAlertDialog.setOnDismissListener(dialog -> {
                SharedPreferencesUtil.clear();
                ActivityUtil.getInstance().finishAllActivity();
                // 跳转到登录页
                Intent intent = new Intent(this, LoginActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                this.startActivity(intent);
            });
        }
        if (!loginOutAlertDialog.isShowing()) {
            loginOutAlertDialog.show();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void networkStatus(boolean isConnected) {

    }

    @Override
    public void networkType(int type) {

    }

    public static void startActivity(Context context) {
        Intent intent = new Intent(context, MainActivity.class);
        context.startActivity(intent);
    }
}